import React, { useEffect, useTransition,useState  } from 'react'
import {Button, Card,Modal,Form,type FormProps, Input,message,Select,Radio,Tree   } from 'antd'
import { ExclamationCircleOutlined  } from '@ant-design/icons'; 
import { useNavigate } from 'react-router-dom';
import { ProFormColumnsType } from '@ant-design/pro-components'
import { addRole, changeRoleStatus, dataScope, delRole, getRole, listRole, updateRole  } from "@/api/system/role";
import { roleMenuTreeselect, treeselect as menuTreeselect } from "@/api/system/menu";
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import md5 from "js-md5"

const { TreeNode } = Tree;  
const { Option } = Select; 
type FieldType = {
    username?: string;
    password?: string;
    phonenumber?:string;
    userId?:number;
    roleId?:number;
  };

const Role = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [modalVisible, setModalVisible] = useState(false);  
  const [userTitle,setUserTitle] = useState("")
  const [menuOptions, setMenuOptions] = useState([]); //角色树 
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [menuIds, setmenuIds] = useState([]); 
  const [form] = Form.useForm();  
  const [onReloadNum,setOnReloadNum] = useState(null)
  const [visData,setVisData] = useState(true)

  const formColumns:ProFormColumnsType[] = [{
    title: '角色编号',
    dataIndex: 'roleId',
    valueType: 'text', 
  },{
    title: '权限字符',
    dataIndex: 'roleKey',
    valueType: 'text', 
  },]


  const columns: any = [
    {
      title: '角色编号',
      dataIndex: 'roleId',
      key: 'roleId',
      width:80,
      fixed:'left',
    },
    {
      title:'角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      width:100,
      fixed:'left',
    },
    {
      title: '权限字符',
      dataIndex: 'roleKey',
      key: 'roleKey',
      width:160,
      fixed:'left',
    },
    {
      title: '显示顺序',
      dataIndex: 'roleSort',
      key: 'roleSort',
      width:80,

    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width:100,
      render: (_, record) => {
        if(record.status == 0){
            return (<>
                <span>正常</span>
              </>)
        }else{
            return (<>
                <span>停用</span>
              </>)
        }
       
    }
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width:100,
      },
    {
        title: t('action'),
        width: 120,
        fixed: 'right',
        render: (_, record) => {
            const handleEdit = () => {  
                //进行弹窗
                setUserTitle('修改角色')
                getRoleMenuTreeselect(record.roleId);
                form.setFieldsValue(record)
                setModalVisible(true);  
              }; 
              const handleRecover = () =>{
                changeRoleStatus(record.roleId,'0').then(response=>{
                  message.success("Success")
                  setOnReloadNum(Date.now())
                }) 
              }
              const showDeleteConfirm = () => {  
                Modal.confirm({  
                  title: 'Confirm Delete Role?',  
                  icon: <ExclamationCircleOutlined />,  
                  okText: '确认/Ok',  
                  cancelText: '取消/Cancel',  
                  onOk() {  
                    console.log(record,'record')
                    changeRoleStatus(record.roleId,'1').then(response=>{
                      message.success("Success")
                      setOnReloadNum(Date.now())
                    }) 
                  },  
                  onCancel() {  
                    console.log('Cancel');  
                  },  
                });  
              } 
              if(record.roleKey == 'admin'){
                //
              }else{
              return (<>
                <Button type='link' onClick={handleEdit}>{t('edit')}</Button>
                {record.status === '1' ? (  
                  <Button type='link' danger onClick={handleRecover}>{t('recover')} </Button>
                ) : (  
                  <Button type='link' danger onClick={showDeleteConfirm}>{t('delete')} </Button>
                )}
              </>)
              }
        }
      }
  ];

/** 根据角色ID查询菜单树结构 */
const getRoleMenuTreeselect = (roleId) =>{
    return roleMenuTreeselect(roleId).then(response => {
        setMenuOptions(response.data.menus)
        setmenuIds(response.data.checkedKeys)
      return response;
    });
  }


  const handleDelete = (roleId) => {
    const id = roleId
    console.log(roleId,'record')
    delRole(id).then(res=>{
        if(res.data.code ==200){
            // 假设你已经处理完数据，关闭弹窗  
            message.success('用户删除成功'); 
            setOnReloadNum(Date.now())
        }else{
            message.error('用户删除失败：' + res.data.msg); 
        }
    })
}

  const handleAdd = () =>{
    form.resetFields()
    setUserTitle('添加角色')
    setmenuIds([])
    setModalVisible(true); 
  }

  const showAllData = () =>{
    setVisData(false)
    setOnReloadNum(Date.now())
  }

  const showNoAllData = () =>{
    setVisData(true)
    setOnReloadNum(Date.now())
  }

  const renderOperator = <>
    <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
    <Button style={{marginLeft:'1%'}} type="primary"  size="small" onClick={showAllData}>{t('allData')}</Button>
    <Button style={{marginLeft:'1%'}} type="primary"  size="small" onClick={showNoAllData}>{t('nonInvisibleData')}</Button>
  </>


  const getData = async (formData) => {
    if(visData==false){
      const { success, data} = await listRole({...formData,status:'' })
      if(!success) return false
      console.log(data)
      const list = data.rows
      return {
        data: list,
        total: data.total
      }
    }else{
      const { success, data} = await listRole({...formData,status:'0' })
      if(!success) return false
      console.log(data)
      const list = data.rows
      return {
        data: list,
        total: data.total
      }
    }
  } 

  useEffect(()=>{
    getTreeSelect()
  },[])
  const getTreeSelect = () =>{
    menuTreeselect().then(res=>{
        console.log(res,'res')
        setMenuOptions(res.data.data)
    })
  }

  const onTreeSelect = (selectedKeys, info) => {  
      // 你可以在这里处理选中节点的逻辑，比如更新表单值等  
      console.log('selectedKeys:', selectedKeys, 'info:', info);
    setSelectedKeys(selectedKeys);  
    
  };  

  const onCheck = (checkedKeysValue) => {
    console.log('onCheck', checkedKeysValue);
    setmenuIds(checkedKeysValue as React.Key[]);
  };
 
 

  const handleModalCancel = () => {  
    form.resetFields(); // 重置表单字段  
    setModalVisible(false);  
  };   


  const handleFormFinish = (values) => {  
    // 处理表单提交逻辑，比如发送API请求  
    values.menuIds = menuIds
    console.log('Form values:', values);
    if(userTitle=='添加角色'){
        values.roleId = ""
        values.menuCheckStrictly = false
        addRole(values).then(res=>{
            console.log(res,'res')
            if(res.data.code ==200){
                // 假设你已经处理完数据，关闭弹窗  
                message.success('角色添加成功');
                handleModalCancel();  
                setOnReloadNum(Date.now())
            }else{
                message.error('角色添加失败：' + res.data.msg); 
            }
        })  
    }else{
        values.roleId = form.getFieldValue('roleId')
        values.menuCheckStrictly=false
        updateRole(values).then(res=>{
            console.log(res,'res')
            if(res.data.code ==200){
                // 假设你已经处理完数据，关闭弹窗  
                message.success('角色更新成功');
                handleModalCancel();  
                setOnReloadNum(Date.now())
            }else{
                message.error('角色更新失败：' + res.data.msg); 
            }
        })  
    }
  
  };  

  return (
    <>
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='roleId'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
     <Modal  
        title={userTitle}  
        visible={modalVisible}  
        onCancel={handleModalCancel}  
        footer={[  
          <Button key="back" onClick={handleModalCancel}>  
            取消  
          </Button>,  
          <Button key="submit" type="primary" onClick={() => form.validateFields().then(handleFormFinish)}> 
            提交  
          </Button>,  
        ]}  
      >  
        <Form form={form} layout="vertical" onFinish={handleFormFinish}>  
          {/* 假设userId是只读的，不需要编辑 */}  
          <Form.Item  
            name="roleName"  
            label="角色名称"  
            rules={[{ required: true, message: '请输入角色名称!' }]}  
          >  
            <Input />  
          </Form.Item>  
  
          <Form.Item  
            name="roleKey"  
            label="权限字符"  
            rules={[{ required: true, message: '请输入权限字符!' }]}  
          >  
            <Input />  
          </Form.Item>  
  
          <Form.Item  
            name="roleSort"  
            label="角色顺序"  
            rules={[{ required: true, message: '请输入角色顺序!' }]} 
          >  
            <Input />  
          </Form.Item>
          <Form.Item  
            name="status"  
            label="状态"  
            // rules={[{ required: true, message: '请输入角色顺序!' }]} 
          >  
            <Radio.Group>  
                <Radio value={'0'}>正常</Radio>  
                <Radio value={'1'}>停用</Radio>  
            </Radio.Group> 
          </Form.Item>
          
          <Form.Item  
            name="menuCheckStrictly"  
            label="菜单权限            "  
          >  
           <Card style={{ maxHeight: '300px', overflowY: 'auto' }}>  
                {/* Tree 组件放置在这里 */}  
             <Tree  
                checkable  
                onSelect={onTreeSelect}
                onCheck={onCheck}  
                multiple  
                checkedKeys={menuIds}
                selectedKeys={selectedKeys}
                treeData={menuOptions}  
                showLine={{ showLeafIcon: false }}  
                blockNode  
                />  
            </Card>
          </Form.Item>
        </Form>   
      </Modal>   
    </>
  )
}
export default Role